<?php

namespace App\Service;

use App\Cache\UserCache;
use App\Model\WxUserModel;
use Hyperf\Di\Annotation\Inject;

class WxUserService
{

    #[Inject(UserCache::class)]
    protected UserCache $userCache;

    /**
     * 通过 $user 更新 数据
     * @param WxUserModel $user
     * @param array $params
     * @return WxUserModel
     */
    public function updateUserByUser(WxUserModel $user, array $params): WxUserModel
    {
        $flag = false;
        foreach ($params as $key => $val) {
            if ($val) {
                $flag |= true;
                $user->$key = $val;
            }
        }
        if ($flag) $user->save();
        return $user;
    }

    public function updateFromById(string $from, string $id): void
    {
        $user = WxUserModel::find($id);
        $user->from = $from;
        $user->save();
        $this->userCache->set($user->openid, $user);
    }

    /**
     * 通过 id 更新数据
     * @param int $id
     * @param array $params
     * @return WxUserModel
     */
    public function updateUserById(int $id, array $params): WxUserModel
    {
        $user = WxUserModel::findOrFail($id);
        return $this->updateUserByUser($user, $params);
    }

    /**
     * 新增一条数据
     * @param array $params
     * @return WxUserModel
     */
    public function insertOne(array $params): WxUserModel
    {
        $userId = WxUserModel::insertGetId($params);
        return WxUserModel::find($userId);
    }

    /**
     * @param string $openid
     * @return WxUserModel
     */
    public function getCachedUserByOpenid(string $openid): WxUserModel
    {
        return $this->userCache->getByOpenid($openid);
    }
}